import {Toast, Dialog} from 'quasar'
import router from '../../router'
export const ctoast = function (text, label) {
  Toast.create({
    html: text,
    timeout: 10000,
    color: '#fff',
    button: {
      label: label,
      handler () {
        // Specify what to do when button is clicked/tapped
      }
    }
  })
}
export const AlertDialog = function (title = '警告', message = '', label = '确认', alertFun = false) {
  let dialog = Dialog.create({
    title: title,
    message: message,
    color: '#cb934b',
    buttons: [
      {
        label: label,
        style: 'color:#cb934b;',
        handler () {
          if (alertFun) {
            dialog.close()
            router.go(-1)
          }
        }
      }
    ]
  })
  return dialog
}
export const confirmDialog = function (message = '', yesFun = () => {
  return false
}, noFun = () => {
  return false
}, title = '提示', yesLabel = '确认', noLabel = '取消') {
  return Dialog.create({
    title: title,
    message: message,
    buttons: [
      {
        label: noLabel,
        classes: 'clear',
        style: 'color:#999;border-right: 1px solid #e5e5e5;',
        handler () {
          noFun()
          // Toast.create('Agreed!')
        }
      },
      {
        label: yesLabel,
        style: 'color:#cb934b',
        handler () {
          yesFun()
          // Toast.create('Disagreed...')
        }
      }
    ]
  })
}

export const checkLen = str => {
  let len = 0
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
      len += 2
    }
    else {
      len++
    }
  }
  return len
}

export const getFormatDate = (timeStr, dateSeparator, timeSeparator, showY = 'true', showM = 'true', showD = 'true', showH = 'true', showMIN = 'true', showSEC = 'true') => {
  /*
   timeStr:时间，格式可为："September 16,2016 14:15:05、
   "September 16,2016"、"2016/09/16 14:15:05"、"2016/09/16"、
   '2014-04-23T18:55:49'和毫秒
   dateSeparator：年、月、日之间的分隔符，默认为"-"，
   timeSeparator：时、分、秒之间的分隔符，默认为":"
   */
  dateSeparator = dateSeparator || '-'
  timeSeparator = timeSeparator || ':'
  let date = new Date(timeStr),
    year = date.getFullYear(), // 获取完整的年份(4位,1970)
    month = date.getMonth(), // 获取月份(0-11,0代表1月,用的时候记得加上1)
    day = date.getDate(), // 获取日(1-31)
    hour = date.getHours(), // 获取小时数(0-23)
    minute = date.getMinutes(), // 获取分钟数(0-59)
    seconds = date.getSeconds(), // 获取秒数(0-59)
    Y = year + dateSeparator,
    M = ((month + 1) > 9 ? (month + 1) : ('0' + (month + 1))) + dateSeparator,
    D = (day > 9 ? day : ('0' + day)) + ' ',
    h = (hour > 9 ? hour : ('0' + hour)) + timeSeparator,
    m = (minute > 9 ? minute : ('0' + minute)) + timeSeparator,
    s = (seconds > 9 ? seconds : ('0' + seconds)),
    formatDate = (showY ? Y : '') + (showM ? M : '') + (showD ? D : '') + (showH ? h : '') + (showMIN ? m : '') + (showSEC ? s : '')
  return formatDate
}
export const WechatShare = function (appId, timestamp, signature = '', nonceStr = '', title = '', link = '', desc = '', imgUrl = '') {
  timestamp = new Date()
  var wx = require('weixin-js-sdk') // 引入sdk
  wx.config({
    debug: true,  // 开启debug
    appId: appId, // 微信appid
    timestamp: timestamp,  // 时间戳
    nonceStr: nonceStr,
    signature: signature, // 签名
    jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'showOptionMenu', 'showAllNonBaseMenuItem'] // 使用的api
  })
  wx.showOptionMenu()
  wx.ready(function () {
    wx.showAllNonBaseMenuItem()
    wx.onMenuShareTimeline({
      title: '', // 分享标题
      link: '', // 分享链接
      desc: '', // 分享描述
      imgUrl: '', // 分享图标
      success: function () {
        alert('分享成功啦！')
      },
      cancel: function () {
        alert('分享失败')
      }
    })
  })
  wx.onMenuShareAppMessage({
    title: '', // 分享标题
    link: '', // 分享链接
    desc: '', // 分享描述
    imgUrl: '', // 分享图标
    type: '', // 分享类型,music、video或link，不填默认为link
    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
    success: function () {
      alert('分享成功啦')
    },
    cancel: function () {
      alert('分享失败')
    }
  })
}
// 第一种修改title的方法
export const setWechatTitle = function (title) {
  document.title = title
  let mobile = navigator.userAgent.toLowerCase()
  if (/iphone|ipad|ipod/.test(mobile)) {
    let iframe = document.createElement('iframe')
    iframe.style.visibility = 'hidden'
    // 替换成站标favicon路径或者任意存在的较小的图即可
    iframe.setAttribute('src', '//m.baidu.com/favicon.ico')
    let iframeCallback = function () {
      setTimeout(function () {
        iframe.removeEventListener('load', iframeCallback)
        document.body.removeChild(iframe)
      }, 10)
    }
    iframe.addEventListener('load', iframeCallback)
    document.body.appendChild(iframe)
  }
}

// 第二种修改title的方法，其中包含iframe的设置：
export const setTitleHack = function (t) {
  document.title = t
  let iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = '1px'
  iframe.style.height = '1px'
  iframe.src = '//m.baidu.com/favicon.ico'
  iframe.onload = function () {
    setTimeout(function () {
      iframe.remove()
    }, 10)
  }
  document.body.appendChild(iframe)
}

/* 设置localstorage */
export const checkPrivateMode = function () {
  try {
    window.localStorage.setItem('ky', 1)
    window.localStorage.removeItem('ky')
    window.isPrivateMode = false
  }
  catch (e) {
    window.isPrivateMode = true
  }
}
export const setLocalstorage = function (name, content) {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  checkPrivateMode()
  if (!window.isPrivateMode && window.localStorage) {
    clearLocalstorage(name)
    localStorage.setItem(name, content)
  }
  else {
    COOKIE.removeItem(name)
    COOKIE.setItem(name, content)
  }
}
export const getLocalstorage = function (name) {
  if (!name) return
  checkPrivateMode()
  if (!window.isPrivateMode && window.localStorage) {
    return window.localStorage.getItem(name)
  }
  else {
    return COOKIE.getItem(name)
  }
}
export const clearLocalstorage = function (name) {
  if (!name) return
  checkPrivateMode()
  if (!window.isPrivateMode && window.localStorage) {
    window.localStorage.removeItem(name)
  }
  else {
    COOKIE.removeItem(name)
  }
}
/* 设置COOKIE */
export const COOKIE = {
  getItem: function (sKey) {
    if (!sKey) {
      return null
    }
    return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(sKey).replace(/[-.+*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    let rge = new RegExp('/^(?:expires|max-age|path|domain|secure)$/i')
    if (!sKey || rge.test(sKey)) {
      return false
    }
    var sExpires = ''
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + vEnd
          break
        case String:
          sExpires = '; expires=' + vEnd
          break
        case Date:
          sExpires = '; expires=' + vEnd.toUTCString()
          break
      }
    }
    document.cookie = encodeURIComponent(sKey) + '=' + encodeURIComponent(sValue) + sExpires + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '') + (bSecure ? '; secure' : '')
    return true
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) {
      return false
    }
    document.cookie = encodeURIComponent(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '')
    return true
  },
  hasItem: function (sKey) {
    if (!sKey) {
      return false
    }
    return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(sKey).replace(/[-.+*]/g, '\\$&') + '\\s*\\=')).test(document.cookie)
  }
}
/* 发送验证码 */
export const verifyTel = function (tel) {
  /* 验证手机号是否正确 */
  if (!tel) {
    AlertDialog('错误', '请填写手机号')
    return false
  }
  else {
    let reg = /^(1[3|4|5|6|7|8|9])\d{9}$/
    if (!reg.test(tel)) {
      AlertDialog('错误', '请填写正确的手机号')
      return false
    }
    else {
      return true
    }
  }
}
